package com.yunao.web.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.yunao.commons.Exception.UserLoginException;
import com.yunao.commons.constant.CookieConstant;
import com.yunao.commons.constant.RedisConstant;
import com.yunao.commons.utils.CookieUtil;
import com.yunao.entity.User;
import com.yunao.service.UserService;
import com.yunao.web.annotation.PassToken;
import com.yunao.web.annotation.UserLoginToken;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.reflect.Method;



public class AuthenticationInterceptor implements HandlerInterceptor {
    @Autowired
    UserService userService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;


    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
//        String token = httpServletRequest.getHeader("token");// 从 http 请求头中取出 token
        // 如果不是映射到方法直接通过
        if (!(object instanceof HandlerMethod)) {
            return true;
        }
                    String token = httpServletRequest.getParameter("token");
                    if (token == null) {
                        throw new UserLoginException("token失效，请重新登录");
                    }
                    // 获取 token 中的 user id
                    String userId = null;
                    try {
                        userId = JWT.decode(token).getAudience().get(0);
                    } catch (JWTDecodeException j) {
                        throw new UserLoginException("token无效，请重新登录");
                    }
                    String redisToken= stringRedisTemplate.opsForValue().get(String.format(RedisConstant.TOKEN_TEMPLATE,userId));
                    if (StringUtils.isEmpty(redisToken)||!redisToken.equals(token))
                        throw new UserLoginException("token无效，请重新登录");
                    int id = Integer.parseInt(userId);
                    User user = userService.findOne(id);
                    if (user == null) {
                        throw new UserLoginException("用户不存在，请重新登录");
                    }
                    // 验证 token
                    JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
                    try {
                        jwtVerifier.verify(token);
                    } catch (JWTVerificationException e) {
                        throw new UserLoginException("token无效，请重新登录");
                    }
                    return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest,
                           HttpServletResponse httpServletResponse,
                           Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest,
                                HttpServletResponse httpServletResponse,
                                Object o, Exception e) throws Exception {
    }
}
